package de.gameduell.framework.chat {
	import de.gameduell.framework.application.controller.IMultiplayerController;
	import de.gameduell.framework.gui.popup.Popup;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.events.TextEvent;
	import flash.text.TextField;	

	/**
	 * @author cbra
	 */
	public class ClickChatPopup extends Popup {
		private var closeButton:Sprite;
		private var clickTextContainer:Sprite;
		private var smileys:Sprite;
		private var _offset:int = 10;
		private var largestObject:Number;
		private var bg:Sprite;
		private var controller:IMultiplayerController;

		public function ClickChatPopup(aController:IMultiplayerController,isResizable:Boolean, libraryID:String,aId:String,aLifetTimer:int = 0,isDraggable:Boolean = false){
			super(libraryID, aId, aLifetTimer, isDraggable);

			closeButton = getChildByName("close") as Sprite;
			closeButton.addEventListener(MouseEvent.CLICK, hide);
			closeButton.buttonMode = true;
			
			controller = aController;
			
			initText(isResizable);
			initSmileys();
			if (isResizable){
				initSize();
			}
		}

		private function initText(isResizable:Boolean):void {
			clickTextContainer = getChildByName("clickText") as Sprite;
			for (var i:int = 0;i < clickTextContainer.numChildren;i++) {
				var clickText:DisplayObject = clickTextContainer.getChildAt(i);
				if (clickText is TextField) {
					if (isResizable){
					updateMaxSize(clickText as TextField);
					}
					clickText.addEventListener(TextEvent.LINK, onHyperlinkClick);
				}
			}
		}

		private function initSmileys():void {
			smileys = getChildByName("smileys") as Sprite;
			for (var i:int = 0;i < smileys.numChildren;i++) {
				var child:DisplayObject = smileys.getChildAt(i);
				if (child is Sprite) {
					var smiley:Sprite = Sprite(child);
					smiley.buttonMode = true;
					smiley.addEventListener(MouseEvent.CLICK, onSmileyClick);
				}
			}
		}

		private function initSize():void {
			updateMaxSize(getChildByName("title")  as TextField);
			bg = getChildByName("bg") as Sprite;
			var maxSize:int = (_offset*2)+largestObject;
			var formerSize:int = bg.width;
			if (formerSize < maxSize){
				bg.width = maxSize;
			}
		}
		
		public function set offset(aOffset:int):void{
			_offset = aOffset;
		}

		private function onHyperlinkClick(event:TextEvent):void {
			controller.sendChatMessage(event.text);
			hide();
		}

		private function onSmileyClick(event:MouseEvent):void {
			controller.sendChatMessage(event.target.name);
			hide();
		}

		private function updateMaxSize(text:TextField):void {
			largestObject = largestObject < text.textWidth ? text.textWidth : largestObject;
		}
	}
}
